package com.mt.restaurant.service.sale.impl;

import com.mt.restaurant.dao.sale.VegetableMenuDao;

import com.mt.common.core.exception.BusinessException;
import com.mt.common.core.web.base.PageDTO;
import com.mt.common.core.web.base.PageResultDTO;
import com.mt.common.core.web.base.BaseEntity;
import com.mt.common.core.web.BaseService;
import com.mt.restaurant.entity.sale.MenuMaterialRelationShip;
import com.mt.restaurant.service.sale.MenuMaterialRelationShipService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.mt.restaurant.entity.sale.VegetableMenu;
import com.mt.restaurant.service.sale.VegetableMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@Transactional
public class VegetableMenuServiceBean extends BaseService implements VegetableMenuService {

    private static Logger logger = LogManager.getLogger();

	@Autowired
	private VegetableMenuDao vegetableMenuDao;

	@Resource
	private RedisTemplate<String, List<VegetableMenu>> redisTemplate;

	@Autowired
	StringRedisTemplate stringRedisTemplate;

	@Autowired
	private MenuMaterialRelationShipService menuMaterialRelationShipService;
	/**
	 * 根据分页参数查询菜谱集合
	 *
	 * @param pageDTO 分页条件
	 */
	@Override
	public PageResultDTO findVegetableMenus(PageDTO pageDTO){
        pageDTO.setStartIndex((pageDTO.getCurrentPage()-1)*pageDTO.getPageSize());
		//TODO:请在此校验参数的合法性
		this.validateFindVegetableMenus(pageDTO);
		List<VegetableMenu> vegetableMenuDTOS = this.vegetableMenuDao.findVegetableMenus(pageDTO);
		Long totalCount = this.vegetableMenuDao.findVegetableMenuTotalCount(pageDTO);

		PageResultDTO pageResultDTO = new PageResultDTO();
		pageResultDTO.setTotalCount(totalCount);
		pageResultDTO.setDatas(vegetableMenuDTOS);

		return pageResultDTO;
	}

	@Override
	public PageResultDTO findVegetableMenusWithCost(PageDTO pageDTO){
        pageDTO.setStartIndex((pageDTO.getCurrentPage()-1)*pageDTO.getPageSize());
		//TODO:请在此校验参数的合法性
		this.validateFindVegetableMenus(pageDTO);
		List<VegetableMenu> vegetableMenuDTOS = this.vegetableMenuDao.findVegetableMenusWithCost(pageDTO);
		Long totalCount = this.vegetableMenuDao.findVegetableMenuTotalCount(pageDTO);

		PageResultDTO pageResultDTO = new PageResultDTO();
		pageResultDTO.setTotalCount(totalCount);
		pageResultDTO.setDatas(vegetableMenuDTOS);

		return pageResultDTO;
	}

	/**
	 * 查询全部菜谱集合
	 *
	 */
	@Override
	public List<VegetableMenu> findAllVegetableMenus(){
		return this.vegetableMenuDao.findAllVegetableMenus();
	}

	/**
	 * 查询所有菜谱集合(只提取ID 和 Name)
	 *
	 */
	@Override
	public List<VegetableMenu> findAllVegetableMenusWithIdName(){
		//TODO:请在此校验参数的合法性
		this.validateFindAllVegetableMenusWithIdName();
		return this.vegetableMenuDao.findAllVegetableMenusWithIdName();
	}

	/**
	 * 根据名称查询菜谱集合(只提取ID 和 Name)
	 *
	 * @param vegetableMenuName 名称
	 */
	@Override
	public List<VegetableMenu> findVegetableMenusWithIdNameByName(String vegetableMenuName){
		//TODO:请在此校验参数的合法性
		this.validateFindVegetableMenusWithIdNameByName(vegetableMenuName);
		//TODO:缓存取对应参数
		Set<String> keys = stringRedisTemplate.keys("searchData:VegetableMenu_where_vegetableMenuName_" + vegetableMenuName);
		List<VegetableMenu> vegetableMenus = new ArrayList<>();
		if (keys.isEmpty()) {
		vegetableMenus = this.vegetableMenuDao.findVegetableMenusWithIdNameByName(vegetableMenuName);
		redisTemplate.opsForValue().set("searchData:VegetableMenu_where_vegetableMenuName_" + vegetableMenuName, vegetableMenus, 30, TimeUnit.DAYS);
		} else {
		vegetableMenus = redisTemplate.opsForValue().get("searchData:VegetableMenu_where_vegetableMenuName_" + vegetableMenuName);
		}
		return vegetableMenus;
	}

	/**
	 * 根据ID查询指定的菜谱(只提取ID 和 Name)
	 *
	 * @param vegetableMenuId Id
	 */
	@Override
	public VegetableMenu findVegetableMenusWithIdNameById(Long vegetableMenuId){
		//TODO:请在此校验参数的合法性
		this.validateFindVegetableMenusWithIdNameById(vegetableMenuId);
		return this.vegetableMenuDao.findVegetableMenusWithIdNameById(vegetableMenuId);
	}

	/**
	 * 根据ID查询指定的菜谱
	 *
	 * @param vegetableMenuId Id
	 */
	@Override
	public VegetableMenu findVegetableMenu(Long vegetableMenuId){
		//TODO:请在此校验参数的合法性
		this.validateFindVegetableMenu(vegetableMenuId);
		return this.vegetableMenuDao.findVegetableMenu(vegetableMenuId);
	}

	/**
	 * 根据ID查询指定的菜谱(包含外键)
	 *
	 * @param vegetableMenuId Id
	 */
	@Override
	public VegetableMenu findVegetableMenuWithForeignName(Long vegetableMenuId){
		//TODO:请在此校验参数的合法性
		this.validateFindVegetableMenuWithForeignName(vegetableMenuId);
		VegetableMenu vegetableMenu = this.vegetableMenuDao.findVegetableMenuWithForeignName(vegetableMenuId);
		if(vegetableMenu.getMenuMaterials().get(0).getEid()==null){
			vegetableMenu.getMenuMaterials().remove(0);
		}
		return this.vegetableMenuDao.findVegetableMenuWithForeignName(vegetableMenuId);
	}

	/**
	 * 新增菜谱
	 *
	 * @param vegetableMenu 实体对象
	 */
	@Override
	public VegetableMenu saveVegetableMenu(VegetableMenu vegetableMenu){
		//TODO:请在此校验参数的合法性
		this.validateSaveVegetableMenu(vegetableMenu);
		//TODO:填充公共参数
		this.setSavePulicColumns(vegetableMenu);

		Long rows = this.vegetableMenuDao.saveVegetableMenu(vegetableMenu);
		List<MenuMaterialRelationShip> menuMaterials = vegetableMenu.getMenuMaterials();
		for (MenuMaterialRelationShip menuMaterialRelationShip:menuMaterials
			 ) {
			menuMaterialRelationShip.setMenuId(vegetableMenu.getEid());
		}

		this.menuMaterialRelationShipService.batchSave(vegetableMenu.getMenuMaterials());
		if(rows != 1)
		{
			String error = "新增保存菜谱出错，数据库应该返回1,但返回了 "+rows;
			throw new BusinessException(error);
		}

		return vegetableMenu;
	}

	/**
	 * 更新菜谱
	 *
	 * @param vegetableMenu 实体对象
	 */
	@Override
	public VegetableMenu updateVegetableMenu(VegetableMenu vegetableMenu){
		//TODO:请在此校验参数的合法性
		this.validateUpdateVegetableMenu(vegetableMenu);
		Long rows = this.vegetableMenuDao.updateVegetableMenu(vegetableMenu);
		if(rows != 1)
		{
			String error = "修改保存菜谱出错，数据库应该返回1,但返回了 "+rows+",数据可能被删除";
			throw new BusinessException(error);
		}
		return vegetableMenu;
	}

	/**
	 * 根据ID删除菜谱
	 *
	 * @param vegetableMenuId ID
	 */
	@Override
	public void deleteVegetableMenu(Long vegetableMenuId){
		//TODO:请在此校验参数的合法性
		this.validateDeleteVegetableMenu(vegetableMenuId);

		Map<Class<? extends BaseEntity>,EntityUsage> entityUsageMap = this.checkForeignEntity(VegetableMenu.class, vegetableMenuId);
		if(entityUsageMap != null && entityUsageMap.size() >0){
			StringBuilder errors = new StringBuilder();
			errors.append("计划删除的数据正在被以下数引用\n");
			for(EntityUsage entityUsage : entityUsageMap.values()){
				errors.append("\t").append(entityUsage.getEntityLabel()).append("\n");
				for(Map.Entry<Long,String> entry : entityUsage.getUsageIdNames().entrySet() ){
					errors.append("\t\t").append(entry.getKey()).append("\t").append(entry.getValue()).append("\n");
				}
			}
			errors.append("，不能删除，请检查处理后再删除");
			throw  new BusinessException(errors.toString());
		}

		Long rows = this.vegetableMenuDao.deleteVegetableMenu(vegetableMenuId);
		if(rows != 1){
			String error = "删除菜谱出错，数据可能已经被删除";
			throw new BusinessException(error);
		}
	}

	@Override
	public void addNewMenu(VegetableMenu vegetableMenu) {

	}

	//TODO:---------------验证-------------------

	private void validateFindVegetableMenus(PageDTO pageDTO) {
	//TODO:请使用下面方法添加数据过滤条件
	//		pageDTO.addFilter("creatorId",this.getLoginUserId());
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateVegetableMenu()写法
	}

	private void validateFindVegetableMenusWithIdNameByName(String vegetableMenuName) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateVegetableMenu()写法
	}


	private void validateFindAllVegetableMenusWithIdName() {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateVegetableMenu()写法
	}

	private void validateFindVegetableMenusWithIdNameById(Long vegetableMenuId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateVegetableMenu()写法
	}

	private void validateFindVegetableMenu(Long vegetableMenuId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateVegetableMenu()写法
	}

	private void validateFindVegetableMenuWithForeignName(Long vegetableMenuId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateVegetableMenu()写法
	}

	private void validateSaveVegetableMenu(VegetableMenu vegetableMenu) {
	//不为空判断
	if (vegetableMenu.getEid() != null || vegetableMenu.getCreatorId() != null || vegetableMenu.getCreateDatetime() != null) {
	throw new BusinessException("非法请求");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateVegetableMenu()写法
	}

	private void validateUpdateVegetableMenu(VegetableMenu vegetableMenu) {
	//不为空判断
	if (vegetableMenu.getEid() == null) {
	throw new BusinessException("唯一标识不能为空");
	}
	//是否存在判断
	if (this.vegetableMenuDao.findVegetableMenuTotalCount(PageDTO.create(VegetableMenu.FIELD_ID, vegetableMenu.getEid())) == 0) {
	throw new BusinessException("修改的菜谱 " + vegetableMenu.getName() + " 不存在，修改失败，请重试或联系管理员");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateVegetableMenu()写法
	}

	private void validateDeleteVegetableMenu(Long vegetableMenuId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateVegetableMenu()写法
	}

	@Override
	public boolean canDownloadAttachment(String formName, Long id) {
	return true;
	}
}
